<?php

namespace app\modules\Merchant\service;

use app\modules\Admin\models\dianpuModel;
use app\modules\Merchant\models\dianpumoneylogModel;
use Illuminate\Database\Capsule\Manager as DB;

class DianpuMoney
{
    public static function moneyChange($money, $dianpu_id, $event, $event_id, $remark = '', $oper_type = 'system', $oper_id = 0): bool
    {
        try {
            $allEvent = dianpumoneylogModel::getAllEvent();
            if(!in_array($event, array_keys($allEvent))){
                throw new \Exception("事件:{$event}不允许");
            }
            if(bccomp($money, 0, 2) === 0){
                throw new \Exception("变动金额：{$money}不能为0");
            }
            //orderPay=订单支付 -,
            //orderRefund=订单退款 +,
            //dianpuWithdraw=申请店铺提现 -,
            //dianpuWithdrawRefund=提现退回 +
            if(in_array($event, ['orderPay', 'dianpuWithdraw']) && bccomp($money, 0, 2) > 0){
                throw new \Exception("扣款事件变动金额：{$money}不能为正数");
            }
            if(in_array($event, ['orderRefund', 'dianpuWithdrawRefund']) && bccomp($money, 0, 2) < 0){
                throw new \Exception("加款事件变动金额：{$money}不能为负数");
            }
            if(dianpuModel::query()->where('id', $dianpu_id)->where('status', 1)->doesntExist()){
                throw new \Exception("店铺不存在或已禁用");
            }
            DB::beginTransaction();
            $dianpu = dianpuModel::query()->lockForUpdate()->find($dianpu_id);
            $before = $dianpu->money;
            $after = bcadd($dianpu->money, $money, 2);
            if(bccomp($after, 0, 2) < 0){
                throw new \Exception("金额不足");
            }
            $dianpu->money = $after;
            if($dianpu->save()){
                $log = [
                    'dianpu_id'=>$dianpu_id,
                    'event'=>$event,
                    'event_id'=>$event_id,
                    'before'=>$before,
                    'money'=>$money,
                    'after'=>$after,
                    'remark'=>$remark,
                    'oper_type'=>$oper_type,
                    'oper_id'=>$oper_id,
                    'created_at'=>timestamp(),
                ];
            }
            dianpumoneylogModel::query()->insert($log);
            DB::commit();
            return true;
        } catch (\Exception $e){
            DB::rollBack();
            trace("Merchant Change Money Error: 店铺ID:{$dianpu_id}, 金额：{$money}, {$e->getMessage()}");
            return false;
        }
    }
}